import { store } from '@/store'
import { defineStore } from 'pinia'
import { accAdd } from '@/utils/formatter'

import * as PayApi from '@/api/shop/trade/pay'

/** 门店会员信息 */
import { useShopUserStoreWithOut } from '@/store/modules/shop/user'
const shopUserStore = useShopUserStoreWithOut()
// const storesKeyboard = useKeyboard()
const message = useMessage() // 消息弹窗
/** 密码键盘信息 */
import { useShopKeyboardWithOut } from './keyBoard'
const shopKeyboard = useShopKeyboardWithOut()
/**
 * 提货操作
 *
 *
 *  */
declare interface State {
  usableList: EmptyArrayType //可用提货商品列表
  useList: any //选中的提货商品列表
  searchType: string //搜索类型
  keywords: string //关键词搜索
  listData: {
    data: EmptyArrayType
    loading: Boolean
    size: number
    current_page: number //当前页
    last_page: number //一共多少页
    total: number
  } //会员列表数据
  employeeList: EmptyArrayType //提货员工列表
  reserveNumber: number //提货数量
  reserveTnum: number //提货种类
  takeTnum: number //待提货种类
  takeNumber: number //待提货件数
  enalePassword: Boolean
  orderBy: string //0 综合排序（默认） 1 时间排序 2 商品排序
}

export const usePick = defineStore('pick', {
  state: (): State => ({
    keywords: '',
    usableList: [], //购物车列表
    useList: [], //选中的提货商品列表
    searchType: 'record', //record 记录 useable //可用

    listData: {
      data: [],
      total: 0,
      loading: false,
      size: 10,
      current_page: 1, //当前页
      last_page: 0 //一共多少页
    }, //列表数据
    employeeList: [], //提货员工列表
    reserveNumber: 0, //提货数量
    reserveTnum: 0, //提货种类
    takeTnum: 0, //待提货种类
    takeNumber: 0, //待提货件数
    enalePassword: true,
    orderBy: '0'
  }),
  getters: {
    Quantity(state) {
      return state.useList.length
    }, //购物车中选择的服务卡项种类
    Total(state) {
      let total = 0
      state.useList.forEach((element: any) => {
        total = accAdd(total, element.opnumber)
      })
      return total
    }, //购物车中选中的服务卡项总数量

    employeeText(state) {
      let employeeText = ''
      state.employeeList.forEach((element: any, index: number) => {
        console.log(element)
        if (index == 0) {
          employeeText += element.employeeId + element.employeeName
        }
      })

      return employeeText
    } //订单信息中销售人展示
  },
  actions: {
    setSearchType(type: string) {
      this.searchType = type
      this.listData = {
        data: [],
        total: 0,
        loading: false,
        size: 10,
        current_page: 1,
        last_page: 0
      }
    }, //设置搜索类型
    setKeywords(keywords: string) {
      this.keywords = keywords
      this.listData.current_page = 1
      this.serchList()
    }, //设置搜索关键词
    setSizeChange(size: number) {
      this.listData.size = size
      this.serchList()
    }, //设置每一页条数
    setCurrentChange(current: number) {
      this.listData.current_page = current
      this.serchList()
    },
    serchList() {
      if (this.searchType == 'record') {
        this.searchRecordList()
      } else if ((this.searchType = 'useable')) {
        this.searchUseableList()
      }
    },
    searchRecordList() {
      console.log(this.orderBy)

      const data = {
        current: this.listData.current_page,
        keyword: this.keywords,
        size: this.listData.size,
        opType: 0,
        userId: shopUserStore.getUser.id,
        orderBy: this.orderBy
      }

      PayApi.orderReserveList(data).then((res) => {
        if (!res.results) {
          return
        }
        const data = res.results
        const records = data.records
        this.listData.data = records
        this.listData.total = data.total
        this.reserveNumber = res.dataMap.reserveNumber
        this.reserveTnum = res.dataMap.reserveTnum

        this.takeTnum = res.dataMap.takeTnum

        this.takeNumber = res.dataMap.takeNumber

        this.enalePassword = res.dataMap.enalePassword
      })
    }, //搜索记录
    async searchUseableList() {
      const params = {
        current: this.listData.current_page,
        keyword: this.keywords,
        size: this.listData.size,
        opType: 1,
        orderBy: this.orderBy,
        userId: shopUserStore.getUser.id
      }

      const data = await PayApi.orderReserveList(params)

      const records = data.records
      this.listData.data = records
      this.listData.total = data.total
      // this.reserveNumber = res.dataMap.reserveNumber
      // this.enalePassword = res.dataMap.enalePassword
    }, //搜索可提货商品记录
    closeCodeKeyBoard() {
      const config = {
        dialogVisible: false,
        title: '请输入密码', //数字键盘弹框的标题
        keyboardValue: ''
      }
      shopKeyboard.setCodeKeyboardConfig(config)
    },
    async orderReserveConfirm(data: any) {
      return new Promise((resolve) => {
        PayApi.orderReserveConfirm(data).then((res) => {
          // 如果res.results 没值就不执行后续代码
          if (!res.ok) {
            return
          }
          this.closeCodeKeyBoard()
          resolve(true)
        })
      })
    }, // 订单提交(支持一键购买)

    async setOrderReserveConfirm() {
      if (this.employeeText == '') {
        message.error('请选择员工')
        return
      }
      if (this.useList?.length == 0) {
        message.error('请选择提货信息')
        return
      }
      const items = this.useList.map((ele: { assetsId: any; opnumber: any }) => {
        return { assetsId: ele.assetsId, opnumber: ele.opnumber }
      })
      if (this.enalePassword) {
        // 如果开启密码验证 并且密码为空时弹出密码框
        if (shopKeyboard.salesPassword == '') {
          this.handleOpenCodeKeyboard()
          return
        } else {
          // 如果有密码校验密码格式
          if (shopKeyboard.salesPassword.length < 6) {
            message.error('密码格式错误')
            return
          }
        }
      }
      //     // 下方便是提交数据
      const paramsData = {
        orderType: 'TH',
        userId: shopUserStore.getUser.id,
        character: 5,
        device: 0, //0 PC
        password: shopKeyboard.salesPassword, //密码
        items: items,
        employeeList: this.employeeList
      }
      const data = await (<any>this.orderReserveConfirm(paramsData))
      if (data) {
        message.success('提货成功')
      }
    }, //设置购物车创建
    setUseList(checkList: EmptyArrayType) {
      this.useList = checkList
    }, //设置选中的提货商品
    setEmployees(employeeList: EmptyArrayType) {
      this.employeeList = employeeList
    },
    handleOpenCodeKeyboard() {
      const codeKeyboardConfig = {
        dialogVisible: true,
        title: '请输入密码', //数字键盘弹框的标题
        keyboardValue: ''
      }
      shopKeyboard.setCodeKeyboardConfig(codeKeyboardConfig)
    }, //打开密码框
    resetState() {
      this.$reset()
    } //清除state
  }
})
export const usePickWithOut = () => {
  return usePick(store)
}
